// miniprogram/pages/add-poster/add-poster.js
const db = wx.cloud.database();
const posterCollection = db.collection("poster")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId:'',
    text :' ',
    remainLen:0,
    fileID:''

  },
  doSubmit(){
    // console.log('1111')
  },
  bindTextInput(e){
    console.log(e);
    const t = e.detail.value;
    this.setData({
      text:t,
      remainLen: t.length
    })
  },
  onImageTap(){
    wx.chooseImage({
      count:1,
      success:(res)=>{
        const tempFilePath = res.tempFilePaths[0]
        //云端
        wx.cloud.uploadFile({
          cloudPath:tempFilePath.replace('//','/').replace(':',""),
          filePath: tempFilePath
        })
        .then(res =>{
          this.setData({
            fileID:res.fileID
          })
          
        })
        .catch(error =>{
          console.log(error,'----');
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('onload..');
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // console.log('onready....');
    wx.hideLoading({
      success: (res) => {},
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // console.log('show.....');
    // wx.showLoading({
    //   title: 'Kannima',
    //   mask:true
    // })
    this.getUserId();
  },
  getUserId(){
    let that = this;
    let val = this.data.userId || wx.getStorageSync('userId');
              console.log(val,'======');
              if(val){
               return val;
               }
    
    wx.getSetting({
      success(res){
        console.log(res)
        if(res.authSetting['scope.userInfo']){
          //小程序可以直接获得用户信息
          wx.getUserInfo({
            withCredentials:true,
            success(userData){
              console.log(userData);
              wx.setStorageSync('userId', userData.signature)
              that.setData({
                userId:userData.signature
              })
              

            }
          })
        }
      }
    })
    this.setData({
     userId: wx.getStorageSync('userId')})
  },
  onSendTap(){
    const posterData = {
      authorId: this.data.userId,
      msg:this.data.text,
      photoId: this.data.fileID,
      date:db.serverDate()
    }
    posterCollection
      .add({
        data:posterData
      })
      .then(res =>{
        console.log(res);
        wx.showToast({
          title: '发送成功',
        })
      })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('hide.....');

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('unload....');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})